<?php

/**
 * Capital Direct Lending (http://www.philbsd.com/cdl)
 *
 * Copyright (C) 2008 Philippine Business Solution Developers <http://www.philbsd.com>
 * All rights reserved.
 *
 *
 * LICENSE
 *
 * This source file is subject to the GNU General Public License v3 license
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.gnu.org/licenses/gpl-3.0.txt
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@philbsd.com so we can send you a copy immediately.
 *
 * @copyright  (c) 2008 Philippine Business Solution Developers. (http://www.philbsd.com)
 * @license    http://www.gnu.org/licenses/gpl-3.0.txt
 * @version    $Id: Auth.php 42 2008-03-12 10:05:35Z philbsd $
 */

class Philbsd_Controller_Plugin_Auth extends Zend_Controller_Plugin_Abstract
{
    public function preDispatch(Zend_Controller_Request_Abstract $request)
    {
        $auth = Zend_Auth::getInstance();

        if ($auth->hasIdentity()) {
			$userProfile = new Philbsd_Model_User_Profiles();
			if ($userProfileRow = $userProfile->fetchRow("username = '{$auth->getIdentity()->username}'")) {
    			$roleRow = $userProfileRow->findParentRow('Philbsd_Model_Roles');
	    		$role = $roleRow->name;
            }
        } else {
            $role = 'guest';
        }

		$request = $this->getRequest();
		$moduleName = $request->getModuleName();
		$controllerName = $request->getControllerName();
		$actionName = $request->getActionName();
		$resourceName = "{$moduleName}.{$controllerName}";

		$acl = Zend_Registry::get('acl');

		
		if (!$acl->has($resourceName)) {
			throw new Exception('Sorry, the requested controller does not exist as an ACL resource');
		}

		if (!$acl->isAllowed($role, $resourceName, $actionName))
		{
            $request->setModuleName('default')
					->setControllerName('user')
                    ->setActionName('login')
                    ->setDispatched(false);
        }
    }
}
